<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="com.gzgi.framework.util.*"%>
<%@ include file="/pages/tm/header.jsp"%>
<%@ include file="/pages/system/checkAdmin.jsp"%>
<%
     
    String sql = request.getParameter("sql");
	if(sql != null){
		SQLFormatter f = new SQLFormatter();
		sql = f.format(sql);
		Connection con = null;
        PreparedStatement psmt = null;
		ResultSet rs = null;
		List rows = new ArrayList();
		StringBuffer buffer = new StringBuffer();
		buffer.append("<table align=\"center\" class=\"x-table-border\" cellspacing=\"1\"")
			  .append(" cellpadding=\"4\" width=\"90%\" nowrap>");
		try {
			con = com.gzgi.framework.context.ContextFactory.getConnection();
			if(sql.trim().toLowerCase().startsWith("select")){
				System.out.println(sql);
				Statement stmt = con.createStatement();
			    rs = stmt.executeQuery(sql);
                ResultSetMetaData rsmd = rs.getMetaData();
				int count = rsmd.getColumnCount();
				Map columnMap = new LinkedHashMap();
				buffer.append("<tr class=\"x-title\" nowrap>\n");
				for (int i = 1; i <= count; i++) {
					String columnName = rsmd.getColumnName(i);
					columnMap.put(columnName, columnName);
					buffer.append("<td align=\"center\"  nowrap>\n");
					buffer.append(columnName.toLowerCase());
                    buffer.append("</td>\n");
				}
				buffer.append("</tr>");
				
				while (rs.next()) {
					int index = 0;
					buffer.append("<tr class=\"x-content\" nowrap>\n");
					Map dataMap = new HashMap();
					Iterator iterator = columnMap.keySet().iterator();
					while (iterator.hasNext()) {
						index++;
						String name = (String) iterator.next();
						String value = rs.getString(index);
						dataMap.put(name.toLowerCase(), value);
						buffer.append("<td align=\"center\" nowrap>\n");
					    buffer.append(value != null ? value : "");
                        buffer.append("</td>\n");
					}
					buffer.append("</tr>\n");
					rows.add(dataMap);
				}
				rs.close();
				stmt.close();
			}
			buffer.append("</table>");
			out.println("<br><div align=center>Commond OK</div><br>");
			out.println(buffer.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex.getMessage());
		} finally{
			try {
				if(con != null){
				    con.close();
			    }
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
%>
<center>
<form method="post" action="">
<textarea name="sql" rows="20" cols="86">
<%=sql != null ? sql : ""%>
</textarea>
<br><br>
<input type="submit" name="submit" value="submit">
</form>
</center>